<template>
  <div class="editor">
    <script :id="editorId" type="text/plain" style="width:100%;height:400px;"></script>
    <!--    <el-dialog-->
    <!--      :visible.sync="videoDialogShowed"-->
    <!--      title="上传视频"-->
    <!--      width="600px"-->
    <!--      :close-on-click-modal="false"-->
    <!--      append-to-body-->
    <!--    >-->
    <!--      <div>-->
    <!--        <sortable-upload :limit="9" accept-type="video" v-model="videoSrcList" :upload-data="{dataType:1}"/>-->
    <!--      </div>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="videoDialogShowed = false">取消</el-button>-->
    <!--        <el-button type="primary" @click="handleSelectVideos">确定</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>

import {SHARDING, UPLOAD_URL} from '@/infra/conf/default'
import {getToken} from '@/utils/auth'
import UploaderUtil from '@/framework/infra/upload/UploaderUtil'
import request from '@/utils/request'

let index = 0
export default {
  name: 'RichEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    uploadDataType: {
      type: [String, Number],
      default: 1
    },
    height: {
      type: String,
      default: '400px'
    },
    placeholder: {
      type: String,
      default: '在这里输入内容'
    }
  },
  data() {
    return {
      editorId: 'editor' + (index++),
      videoDialogShowed: false,
      videoSrcList: []
    }
  },
  watch: {
    value: {
      handler(value) {
        // if (this.hasChanged) {
        //   this.hasChanged = false
        //   return
        // }
        if (value === null) {
          value = ''
        }
        this._initEditor()
        this.setContent(value)
      },
      immediate: true
    }
  },
  deactivated() {
    this.ue && this.ue.removeListener('contentChange', this.contentChangeHandler)
    this.ue && this.ue.removeListener('ready', this.handleReady)
  },
  beforeDestroy() {
    if (this.ue && this.ue.destroy) {
      this.ue.destroy()
      this.ue = null
    }
  },
  methods: {
    handleReady() {
      this.isReady = true
      this.setContent(this.value)
    },
    contentChangeHandler() {
      const content = this.ue.getContent()
      // this.hasChanged = true
      this.$emit('input', content)
    },
    setContent(value) {
      if (this.isReady) {
        const content = this.ue.getContent()
        if (content === value) {
          return
        }
        // console.log('set content')
        // console.log(value)
        this.ue.setContent(value)
      }
    },
    _initEditor() {
      if (!this.ue) {
        this.$nextTick(() => {
          // eslint-disable-next-line no-undef
          this.ue = UE.getEditor(this.editorId, {
            zIndex: 100000,
            imageActionName: 'image',
            autoHeightEnabled: false,
            initialFrameHeight: 500,
            initialFrameWidth: '100%',
            videoFieldName: 'chunkData',
            serverUrl: '/ueditor-1.4.3.3/config/config.json',
            autoFloatEnabled: false,
            VIDEO_UPLOAD_URL: UPLOAD_URL,
            // 上传视频之前
            beforeSendVideoFile(file, data, header, next) {
              header['Authorization'] = getToken()
              header['token'] = getToken()
              console.log(file, 'file')
              data['file'] = file.source.source
              next()
              // UploaderUtil.initTrunk({
              //   request, shardingUrl: SHARDING, uploadData: {
              //     dataType: 1
              //   },
              //   file
              // }).then(res => {
              //   Object.assign(data, res)
              //   next()
              // })
            },
            // file.source
            uploadVideoSuccess(file, data) {
              console.log(file, data)
              return new Promise((resolve, reject) => {
                resolve(data.partETags?.[0]) 
              })
            },
            // 上传图片之前
            beforeUpload: (input, editor) => {
              return new Promise((resolve, reject) => {
                UploaderUtil.uploadFile({
                  request,
                  uploadData: {type: this.uploadDataType},
                  uploadUrl: UPLOAD_URL
                },
                {
                  file: input.files[0],
                  // progress: (progress) => {
                  //   uploadItem.progress = progress
                  // },
                  success: (res) => {
                    resolve({
                      state: 'SUCCESS',
                      url: res
                    })
                  },
                  error: (err) => {
                    resolve({
                      state: err.message
                    })
                  }
                })
              })
            }
          })
          this.ue.addListener('ready', this.handleReady)
          this.ue.addListener('contentChange', this.contentChangeHandler)
        })
      }
    }
  }
}
</script>

<style scoped>
.editor {
  line-height: 1;
  /*margin-bottom: 70px;*/
}
</style>
